<template>
  <div class="page">
    <el-container>
      <el-main>
        <!-- 上传数据对话框 -->
        <el-dialog
          title="上传数据"
          modal-append-to-body="false"
          append-to-body="true"
          :visible.sync="uploadDialogVisible"
          width="500px"
          top="50px"
        >
          <el-form :model="uploadForm" label-width="100px">
            <el-form-item label="数据类型">
              <el-select v-model="uploadForm.type" placeholder="请选择数据类型">
                <el-option label="矢量数据" value="vector"></el-option>
                <el-option label="栅格影像" value="raster"></el-option>
                <el-option label="JSON数据" value="json"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="年份" prop="year">
              <el-date-picker
                v-model="uploadForm.year"
                type="year"
                format="yyyy"
                value-format="yyyy"
                placeholder="选择年份"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="选择文件">
              <el-upload
                class="upload-demo"
                :auto-upload="false"
                :on-change="handleFileChange"
                :show-file-list="false"
              >
                <el-button size="small" type="primary">点击选择文件</el-button>
                <span v-if="uploadForm.file" class="file-name">{{
                  uploadForm.file.name
                }}</span>
              </el-upload>
            </el-form-item>
            <el-form-item label="图片" prop="image">
              <el-upload
                class="image-uploader"
                action=""
                :auto-upload="false"
                :on-change="handleImageChange"
                :show-file-list="false"
              >
                <img
                  v-if="uploadForm.imageUrl"
                  :src="uploadForm.imageUrl"
                  class="image-preview"
                />
                <i v-else class="el-icon-plus image-uploader-icon"></i>
              </el-upload>
              <div class="image-tip">点击上传图片</div>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
            <el-button
              type="primary"
              :disabled="!uploadForm.file"
              @click="uploadData"
            >
              确 定
            </el-button>
          </span>
        </el-dialog>

        <el-card class="data-list-card" :body-style="{ padding: '0px 20px' }">
          <div slot="header" class="card_header">
            <el-button
              type="primary"
              icon="el-icon-upload"
              @click="showUploadDialog"
            >
              上传数据
            </el-button>
            <el-select
              v-model="filterType"
              placeholder="过滤类型"
              class="filter-select"
              size="medium"
            >
              <el-option label="全部" value="all"></el-option>
              <el-option label="矢量数据" value="vector"></el-option>
              <el-option label="栅格影像" value="raster"></el-option>
              <el-option label="JSON数据" value="json"></el-option>
            </el-select>
          </div>

          <el-table
            :data="filteredData"
            style="width: 100%"
            empty-text="暂无数据"
          >
            <el-table-column width="55"> </el-table-column>
            <el-table-column
              prop="name"
              label="文件名"
              width="180"
            ></el-table-column>
            <el-table-column label="图片" width="120">
              <template slot-scope="scope">
                <el-popover
                  placement="right"
                  trigger="hover"
                  v-if="scope.row.imageUrl"
                >
                  <img
                    :src="scope.row.imageUrl"
                    style="max-width: 200px; max-height: 200px"
                  />
                  <img
                    slot="reference"
                    :src="scope.row.imageUrl"
                    style="width: 50px; height: 50px; cursor: pointer"
                  />
                </el-popover>
                <span v-else>无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="180">
              <template slot-scope="scope">
                <el-tag :type="getTagType(scope.row.type)">
                  {{ getTypeName(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="year"
              label="年份"
              width="100"
            ></el-table-column>

            <el-table-column prop="size" label="大小" width="180">
              <template slot-scope="scope">
                {{ formatSize(scope.row.size) }}
              </template>
            </el-table-column>

            <el-table-column prop="lastModified" label="上传时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.lastModified) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="180">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click="downloadData(scope.row)"
                >
                  下载
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteData(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      uploadDialogVisible: false, // 控制上传对话框显示
      uploadForm: {
        type: "vector",
        year: "",
        image: null,
        imageUrl: "",
        file: null,
      },
      filterType: "all",
      dataItems: JSON.parse(localStorage.getItem("dataItems")) || [],
      nextId: JSON.parse(localStorage.getItem("nextId")) || 1,
    };
  },
  computed: {
    filteredData() {
      if (this.filterType === "all") {
        return this.dataItems;
      }
      return this.dataItems.filter((item) => item.type === this.filterType);
    },
  },
  methods: {
    // 显示上传对话框
    showUploadDialog() {
      this.uploadDialogVisible = true;
      // 重置表单
      this.uploadForm = {
        type: "vector",
        year: "",
        file: null,
        image: null,
        imageUrl: "",
      };
    },

    handleFileChange(file) {
      this.uploadForm.file = file.raw;
    },
    handleImageChange(file) {
      const isImage = file.raw.type.includes("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件");
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB");
        return false;
      }

      this.uploadForm.image = file.raw;
      this.uploadForm.imageUrl = URL.createObjectURL(file.raw);
    },
    uploadData() {
      if (!this.uploadForm) {
        this.$message.error("请填写完整信息");
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const imageReader = new FileReader();

        if (this.uploadForm.image) {
          imageReader.onload = (imageEvent) => {
            this.saveDataItem(e.target.result, imageEvent.target.result);
          };
          imageReader.readAsDataURL(this.uploadForm.image);
        } else {
          this.saveDataItem(e.target.result, "");
        }
      };

      if (this.uploadForm.type === "json") {
        reader.readAsText(this.uploadForm.file);
      } else {
        reader.readAsDataURL(this.uploadForm.file);
      }
    },
    saveDataItem(data, imageData) {
      const newItem = {
        id: this.nextId++,
        name: this.uploadForm.file.name,
        type: this.uploadForm.type,
        year: this.uploadForm.year,
        size: this.uploadForm.file.size,
        lastModified: new Date().toISOString(),
        data: data,
        imageUrl: imageData,
      };

      this.dataItems.unshift(newItem);
      this.saveToLocalStorage();
      this.uploadDialogVisible = false;
      this.$message.success("上传成功");
    },
    deleteData(id) {
      this.$confirm("确定要删除这条数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dataItems = this.dataItems.filter((item) => item.id !== id);
          this.saveToLocalStorage();
          this.$message.success("删除成功");
        })
        .catch(() => {
          //this.$message.info("已取消删除");
        });
    },

    downloadData(item) {
      let blob, filename;
      if (item.type === "json") {
        blob = new Blob([item.data], { type: "application/json" });
        filename = item.name.endsWith(".json")
          ? item.name
          : `${item.name}.json`;
      } else {
        const byteString = atob(item.data.split(",")[1]);
        const mimeString = item.data.split(",")[0].split(":")[1].split(";")[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);

        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }

        blob = new Blob([ab], { type: mimeString });
        filename = item.name;
      }

      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      this.$message.success("开始下载");
    },
    saveToLocalStorage() {
      localStorage.setItem("dataItems", JSON.stringify(this.dataItems));
      localStorage.setItem("nextId", JSON.stringify(this.nextId));
    },

    getTypeName(type) {
      const types = {
        vector: "矢量数据",
        raster: "栅格影像",
        json: "JSON数据",
      };
      return types[type];
    },

    getTagType(type) {
      const types = {
        vector: "success",
        raster: "warning",
        json: "info",
      };
      return types[type];
    },

    formatSize(size) {
      if (size < 1024) {
        return `${size} B`;
      } else if (size < 1024 * 1024) {
        return `${(size / 1024).toFixed(2)} KB`;
      } else {
        return `${(size / (1024 * 1024)).toFixed(2)} MB`;
      }
    },

    formatDate(dateString) {
      return new Date(dateString).toLocaleString();
    },
  },
};
</script>

<style scoped>
.page {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    Arial, sans-serif;
  margin: 0 auto;
}
.el-main {
  padding: 10px;
}
.upload-btn-container {
  margin-bottom: 10px;
}

.data-list-card {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.data-list-card .card_header span {
  font-size: 16px;
  line-height: 36px;
}
.el-table__header-wrapper {
  overflow: hidden;
}
.filter-select {
  margin: 0 10px;
  /* float: right; */
  width: 120px;
}

.file-name {
  margin-left: 10px;
  color: #606266;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin-right: 5px;
}
/* 图片上传样式 */
.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.image-preview {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.image-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>